package com.zookeeper;

import org.apache.zookeeper.*;
import java.util.concurrent.CountDownLatch;

//生成分布式的id
public class MyUniqueId implements Watcher {

    private final String CONNECT_ADDRESS = "192.168.1.120";
    private final Integer SESSIONT_IMEOUT = 5 * 1000;
    private static ZooKeeper zk;
    private String defaultPath="/uniqueId";
    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public void process(WatchedEvent event) {
        if (event.getState()==Event.KeeperState.SyncConnected){
            countDownLatch.countDown();
            System.out.println("连接成功");
        }
    }

    public String getUniqueId(){
        String path="";
        try {
            zk=new ZooKeeper(CONNECT_ADDRESS,SESSIONT_IMEOUT,this);
            countDownLatch.await();
            //节点的权限策略是所有人都有最高权限，创建的是临时有序节点
            path=zk.create(defaultPath,new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        }catch (Exception e){
            e.printStackTrace();
        }
        //截取从第9个字符串往后的字符串，可以作为分布式的id
        return path.substring(9);
    }

    public static void main(String[] args) {
        MyUniqueId myUniqueId = new MyUniqueId();
        for (int i = 0; i < 4; i++) {
            System.out.println(myUniqueId.getUniqueId());
        }
    }
}
